﻿using MediatR;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Hosting;
using System;

namespace B.S.Meeting.WriteAPI.Controllers
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class ImageController : ControllerBase
    {
        IConfiguration configuration;
        IWebHostEnvironment environment;
        IMediator mediator;
        ILogger<ImageController> logger;
        public ImageController(IMediator mediator, ILogger<ImageController> logger, IWebHostEnvironment environment, IConfiguration configuration)
        {
            this.mediator = mediator;
            this.logger = logger;
            this.environment = environment;
            this.configuration = configuration;
        }

        [HttpPost]
        public async Task<dynamic> UploadFile(IFormFile file)
        {
            var filesize = file.Length / 1024 ;//文件大小
            if (filesize > Convert.ToInt64(configuration["uploadConfig:Limit"]))
            {
                throw new Exception("文件大小超过限制");
            }
            var fileExt = Path.GetExtension(file.FileName).ToLower();
            if (!configuration["uploadConfig:ExtName"].Split(',').Contains(fileExt.Trim('.')))
            {
                throw new Exception("文件格式不正确，请上传");
            }
            Directory.CreateDirectory($"{environment.WebRootPath}/UploadFiles/images/{DateTime.Now.ToString("yyyyMMdd")}/");
            var newfileName = $"{DateTime.Now.ToString("yyyyMMddHHmmss")}-{Random.Shared.Next(1000, 9999)}{fileExt}";
            var filePath = $"{environment.WebRootPath}/UploadFiles/images/{DateTime.Now.ToString("yyyyMMdd")}/{newfileName}";
            using (var stream = System.IO.File.Create(filePath))
            {
                 file.CopyTo(stream);
                stream.Close();
            }
            return $"/UploadFiles/images/{DateTime.Now.ToString("yyyyMMdd")}/{newfileName}";
        }
    }
}
